package com.ruoyi.file.service;

import com.ruoyi.common.core.exception.base.BaseException;
import com.ruoyi.file.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 本地文件存储
 * 
 * @author ruoyi
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService
{
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;
    
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     */
    @Override
    public String uploadFile(MultipartFile file)  {

        String[] strings = {"pdf","doc","docx","jpg","jpeg","png","zip","rar"};

        //判断文件格式是否符合要求
        boolean allowedExtension = FileUploadUtils.isAllowedExtension(FileUploadUtils.getExtension(file), strings);
        if(!allowedExtension)  throw new BaseException("文件格式不符合要求");

//        String replace = file.getName().replace(" ", "_");


        String name = null;
        try {
            name = FileUploadUtils.upload(localFilePath, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = domain + localFilePrefix + name;
        return url;
    }
}
